﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowCaptureWithResultDisplay
{
    public partial class MainForm : Form
    {
        // 热键相关常量
        private const int WM_HOTKEY = 0x0312;
        private const int HOTKEY_ID_1 = 1;
        private const int HOTKEY_ID_2 = 2;
        private const int HOTKEY_ID_3 = 3;

        // HttpClient实例
        private static readonly HttpClient _httpClient = new HttpClient();

        // 当前截图缓存
        private Bitmap _currentCapture;

        public MainForm()
        {
            InitializeComponent();
            radioType1.Checked = true;
            RegisterHotKeys();

            // 设置返回消息文本框为只读
            txtResponse.ReadOnly = true;
            txtResponse.ScrollBars = ScrollBars.Vertical;
            txtResponse.Multiline = true;
            txtResponse.WordWrap = true;
        }

        // 注册热键
        private void RegisterHotKeys()
        {
            NativeMethods.RegisterHotKey(this.Handle, HOTKEY_ID_1, NativeMethods.MOD_CONTROL, (int)Keys.D1);
            NativeMethods.RegisterHotKey(this.Handle, HOTKEY_ID_2, NativeMethods.MOD_CONTROL, (int)Keys.D2);
            NativeMethods.RegisterHotKey(this.Handle, HOTKEY_ID_3, NativeMethods.MOD_CONTROL, (int)Keys.D3);
        }

        // 注销热键
        private void UnregisterHotKeys()
        {
            NativeMethods.UnregisterHotKey(this.Handle, HOTKEY_ID_1);
            NativeMethods.UnregisterHotKey(this.Handle, HOTKEY_ID_2);
            NativeMethods.UnregisterHotKey(this.Handle, HOTKEY_ID_3);
        }

        // 处理热键消息
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_HOTKEY)
            {
                switch (m.WParam.ToInt32())
                {
                    case HOTKEY_ID_1:
                        radioType1.Checked = true;
                        TriggerCapture();
                        break;
                    case HOTKEY_ID_2:
                        radioType2.Checked = true;
                        TriggerCapture();
                        break;
                    case HOTKEY_ID_3:
                        radioType3.Checked = true;
                        TriggerCapture();
                        break;
                }
            }
            base.WndProc(ref m);
        }

        // 触发截图和上传
        private async void TriggerCapture()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(TriggerCapture));
                return;
            }

            btnCaptureAndUpload.Enabled = false;
            lblStatus.Text = "热键触发 - 正在处理...";

            try
            {
                string selectedType = radioType1.Checked ? "0" :
                                    radioType2.Checked ? "1" : "2";

                await CaptureAndUploadWindowAsync(selectedType);
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"错误: {ex.Message}";
                txtResponse.Text = $"发生错误:\r\n{ex.ToString()}";
            }
            finally
            {
                btnCaptureAndUpload.Enabled = true;
            }
        }

        // 按钮点击事件
        private async void btnCaptureAndUpload_Click(object sender, EventArgs e)
        {
            btnCaptureAndUpload.Enabled = false;
            lblStatus.Text = "正在处理...";

            try
            {
                string selectedType = radioType1.Checked ? "0" :
                                    radioType2.Checked ? "1" : "2";

                await CaptureAndUploadWindowAsync(selectedType);
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"错误: {ex.Message}";
                txtResponse.Text = $"发生错误:\r\n{ex.ToString()}";
            }
            finally
            {
                btnCaptureAndUpload.Enabled = true;
            }
        }

        // 捕获并上传窗口
        public async Task CaptureAndUploadWindowAsync(string type)
        {
            // 释放之前的截图
            if (_currentCapture != null)
            {
                _currentCapture.Dispose();
                _currentCapture = null;
            }

            // 获取前台窗口
            IntPtr hWnd = NativeMethods.GetForegroundWindow();
            if (hWnd == IntPtr.Zero)
            {
                lblStatus.Text = "错误: 无法获取活动窗口";
                return;
            }

            // 获取窗口位置和大小
            NativeMethods.RECT rect;
            NativeMethods.GetWindowRect(hWnd, out rect);

            // 确保窗口大小有效
            int width = rect.Right - rect.Left;
            int height = rect.Bottom - rect.Top;

            if (width <= 0 || height <= 0)
            {
                lblStatus.Text = "错误: 窗口大小无效";
                return;
            }

            // 创建位图
            _currentCapture = new Bitmap(width, height);

            // 使用前台截图方式
            using (Graphics g = Graphics.FromImage(_currentCapture))
            {
                // 将窗口内容拷贝到位图
                g.CopyFromScreen(rect.Left, rect.Top, 0, 0, new Size(width, height));
            }

            // 将图像转换为字节数组
            byte[] imageData;
            using (MemoryStream ms = new MemoryStream())
            {
                _currentCapture.Save(ms, ImageFormat.Png);
                imageData = ms.ToArray();
            }

            // 上传到服务器
            await UploadImageAsync(imageData, type);

            // 截图完成提示
            lblStatus.Text = $"截图完成，类型: {type} (点击预览按钮查看)";
        }

        // 显示预览对话框
        private void ShowPreviewDialog()
        {
            if (_currentCapture == null)
            {
                MessageBox.Show("没有可预览的截图", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Form previewForm = new Form
            {
                Text = "截图预览 - " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                StartPosition = FormStartPosition.CenterParent,
                FormBorderStyle = FormBorderStyle.Sizable,
                WindowState = FormWindowState.Normal,
                Size = new Size(800, 600)
            };

            PictureBox pictureBox = new PictureBox
            {
                Dock = DockStyle.Fill,
                SizeMode = PictureBoxSizeMode.Zoom,
                Image = (Image)_currentCapture.Clone()
            };

            Button btnClose = new Button
            {
                Text = "关闭(&C)",
                Dock = DockStyle.Bottom,
                Height = 40,
                DialogResult = DialogResult.OK
            };

            previewForm.Controls.Add(pictureBox);
            previewForm.Controls.Add(btnClose);
            previewForm.AcceptButton = btnClose;

            // 显示为模态对话框
            previewForm.ShowDialog(this);
        }

        // 上传图片
        private async Task UploadImageAsync(byte[] imageData, string type)
        {
            try
            {
                string uploadUrl = "https://sg.zhy1024.com/detect";

                using (var content = new MultipartFormDataContent())
                {
                    content.Add(new StringContent(type), "type");

                    var imageContent = new ByteArrayContent(imageData);
                    imageContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/png");
                    content.Add(imageContent, "image", $"screenshot_{DateTime.Now:yyyyMMddHHmmss}.png");

                    lblStatus.Text = "正在上传...";
                    txtResponse.Text = "正在上传图片到服务器...";

                    var response = await _httpClient.PostAsync(uploadUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string message = await response.Content.ReadAsStringAsync();
                        lblStatus.Text = $"上传成功! 类型: {type}";

                        // 格式化返回消息
                        //txtResponse.Text = $"上传成功!\r\n" +
                        //                 $"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\r\n" +
                        //                 $"类型: {type}\r\n" +
                        //                 $"服务器响应:\r\n" +
                        //                 $"{FormatJsonResponse(message)}";


                        string msg = "";
                        Color back = Color.FromArgb(255, 200, 200);
                        if (type == "0" || type == "1")
                        {
                          
                            radioType1.Checked = true;
                            msg = "'路线颜色为背景色，洞口为： " + message;
                            if (message == "1")
                            {
                                back = Color.FromArgb(115, 146, 57);
                            }
                            else if (message == "2")
                            {
                                back = Color.FromArgb(49, 52, 90);
                            }
                            else if (message == "3")
                            {
                                back = Color.FromArgb(57, 158, 148);

                            }
                            else if (message == "4")
                            {
                                back = Color.FromArgb(156, 60, 165);
                            }
                            else if (message == "5")
                            {
                                back = Color.FromArgb(148, 40, 33);
                            }
                            else if (message == "6")
                            {
                                back = Color.FromArgb(52, 119, 65);
                            }
                            else
                            {
                                msg = message;
                                radioType2.Checked = true;
                            }
                        }
                        else
                        {
                            msg = message;
                        }
                        txtResponse.Text = msg;
                        txtResponse.BackColor = back;
                    }
                    else
                    {
                        string errorText = await response.Content.ReadAsStringAsync();
                        lblStatus.Text = $"上传失败: {response.StatusCode}";
                        txtResponse.Text = $"上传失败!\r\n" +
                                         $"状态码: {response.StatusCode}\r\n" +
                                         $"错误信息:\r\n" +
                                         $"{errorText}";
                    }
                }
            }
            catch (HttpRequestException httpEx)
            {
                lblStatus.Text = $"网络错误: {httpEx.Message}";
                txtResponse.Text = $"网络连接错误:\r\n{httpEx.ToString()}";
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"上传错误: {ex.Message}";
                txtResponse.Text = $"发生错误:\r\n{ex.ToString()}";
            }
        }

        // 格式化JSON响应
        private string FormatJsonResponse(string json)
        {
            try
            {
                // 简单的JSON格式化，增加可读性
                return json.Replace("{", "{\r\n  ")
                          .Replace(",", ",\r\n  ")
                          .Replace("}", "\r\n}");
            }
            catch
            {
                return json;
            }
        }

        // 保存截图
        private void btnSaveScreenshot_Click(object sender, EventArgs e)
        {
            if (_currentCapture == null)
            {
                MessageBox.Show("没有可保存的截图", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "PNG图片|*.png|JPEG图片|*.jpg|BMP图片|*.bmp";
                sfd.Title = "保存截图";
                sfd.FileName = $"截图_{DateTime.Now:yyyyMMddHHmmss}";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    ImageFormat format = ImageFormat.Png;
                    switch (Path.GetExtension(sfd.FileName).ToLower())
                    {
                        case ".jpg":
                        case ".jpeg":
                            format = ImageFormat.Jpeg;
                            break;
                        case ".bmp":
                            format = ImageFormat.Bmp;
                            break;
                    }

                    _currentCapture.Save(sfd.FileName, format);
                    lblStatus.Text = $"截图已保存到: {sfd.FileName}";
                    txtResponse.Text = $"截图已保存到:\r\n{sfd.FileName}\r\n" +
                                     $"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
                }
            }
        }

        // 单选按钮变化事件
        private void radioType_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is RadioButton radio && radio.Checked)
            {
                lblStatus.Text = $"已选择类型 {(radio == radioType1 ? "0" : radio == radioType2 ? "1" : "2")}";
            }
        }

        // 窗体关闭事件
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            UnregisterHotKeys();
            if (_currentCapture != null)
            {
                _currentCapture.Dispose();
            }
            base.OnFormClosing(e);
        }

        // 预览按钮点击事件
        private void btnShowPreview_Click(object sender, EventArgs e)
        {
            ShowPreviewDialog();
        }
    }

    // 封装Native方法
    internal static class NativeMethods
    {
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll")]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        public const int MOD_CONTROL = 0x0002;

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    }
}